<?php
class StudentsController extends AppController {

    public $name = 'Students';
    protected $searchable = array(
        'number' => null,
        'class' => null,
        'political' => null,
        'gender' => null,
        'student_minority_id' => null,
        'student_province_id' => null
    );
    public $paginate = array(
        'order' => 'Student.created DESC',
        'contain' => array(
            'StudentMinority' => array('id', 'name'),
            'StudentProvince' => array('id', 'name')
        )
    );

    public function index(){
        $this->_justifyPaginator();
        $this->set('students', $this->paginate());
    }

    public function home(){
        $this->set('student', $this->Student->find('first', array(
            'conditions'=>array('Student.name' => $this->user['name']),
            'contain' => array(
                'StudentResume',
                'StudentProvince',
                'StudentMinority'
            )
        )));
    }

    public function view($id = null){
        if(!$id){
            $this->redirect(array('action'=>'home'));
        }
        $this->set('student', $this->Student->find('first', array(
            'conditions'=>array('Student.id' => $id),
            'contain' => array(
                'StudentResume',
                'StudentProvince',
                'StudentMinority'
            )
        )));
    }

    public function add(){
        if(!empty($this->data)){
            $this->Student->create();
            if($this->Student->save($this->data)){
                $this->Session->setFlash(__('The Student has been saved', true));
                $this->redirect(array('action'=>'index'));
            }else{
                $this->Session->setFlash(__('The Student could not be saved. Please, try again.', true));
            }
        }
        $studentMinorities = $this->Student->StudentMinority->find('list');
        $studentProvinces = $this->Student->StudentProvince->find('list');
        $this->set(compact('studentMinorities', 'studentProvinces'));
    }

    public function edit($id = null){
        if(!$id && empty($this->data)){
            $this->Session->setFlash(__('Invalid Student', true));
            $this->redirect(array('action'=>'index'));
        }
        if(!empty($this->data)){
            if($this->Student->save($this->data)){
                $this->Session->setFlash(__('The Student has been saved', true));
                if(isset($this->data['Student']['number']) && isset($this->data['Student']['email'])){
                    $this->loadModel('User');
                    $this->User->id = $this->User->field('id', 'User.username="'.$this->data['Student']['number'].'"');
                    $this->User->set(array('email'=>$this->data['Student']['email']));
                    $this->User->save();
                }
                $this->redirect(array('action'=>'home'));
            }else{
                $this->Session->setFlash(__('The Student could not be saved. Please, try again.', true));
            }
        }
        if(empty($this->data)){
            $this->data = $this->Student->read(null, $id);
            $this->set('student', $this->data['Student']);
        }
        $studentMinorities = $this->Student->StudentMinority->find('list');
        $studentProvinces = $this->Student->StudentProvince->find('list');
        $this->set(compact('studentMinorities','studentProvinces'));
    }

    /* View application details */
    public function job($student_id=null){
        /* If no user specified, we use the logged in student */
        if(!$student_id && ($this->user['group'] == 'student')){
            $student_id = $this->user['student']['id'];
        }

        /* If no specified or not login, redirect to home page */
        if(!$student_id){
            $this->Session->setFlash(__('You are not logged in or not allowed to do this', true));
            $this->redirect(array('action'=>'home'));
        }
        $this->set('student', $this->Student->getJobData($student_id));
    }

    /* Search for an keywords */
    public function search(){}

    /* Import student data to the database, here we have some tricks
        As the uploaded file does not belong to any Model, we assign it to the temp user,
        that is to say, each data file to import is treated and transfered as an User Attachment,
        after importing of data, we just keep every imported file and that makes up an histroy,
        model.User: in charge of file upload and retrieve;
        model.Student: incharge of file parsing and data importing
    */
    public function import(){
        $logs = array();
        $data = $this->data;
        if($this->__isCsvFileUploaded()){
            $logs[] = 'Loading model.User and model.Group ...';
            $this->loadModel('User');
            $this->loadModel('Group');
            extract($this->Student->import(array(
                'data' => $this->data,
                'log' => 'database',
                'logs' => &$logs,
                'user' => &$this->User,
                'group' => &$this->Group,
                'password' => $this->Auth->password('000000'),
                'merge' => $this->data['User']['merge']
            )));
        }elseif($this->data){
             $logs[] = 'Error: No valid file provided';
             $logs[] = 'Expecting valid CSV File encoded with UTF-8';
        }
        $this->set(compact('logs', 'data'));
    }
    /* Check if there are actually file uploaded */
    private function __isCsvFileUploaded(){
        $name = $this->data['Attachment'][0]['file']['name'];
        return !empty($name) && (strpos($name, '.csv') !== false);
    }

    /* Export student info as CSV */
    public function export(){
        $specified = $this->__isExportFieldSpecified();
        if($specified){
            $csv = $this->Student->export($specified);
            $this->Response->csv($csv);
        }else{
            $schemas = $this->Student->export();
            $this->set(compact('specified', 'schemas'));
        }
    }
    /* Check if we have exported, else return that are not empty  */
    private function __isExportFieldSpecified(){
        if(empty($this->data)){
            return false;
        }
        /* Define an empty query object */
        $specified = array(
            'fields' => array(),
            'order' => null,
            'conditions' => array()
        );
        /* Handle posted fields */
        $data = $this->data['Student']['export'];
        $fields = $data['fields'];
        foreach($fields as $field=>$value){
            if($value){
                $specified['fields'][] = $field;
            }
        }
        /* Set sort orders */
        $specified['order'] = 'Student.'.$data['order']['by'];
        $specified['order'] .= $data['order']['order'] ? ' ASC' : ' DESC';
        return $specified;
    }

}
?>